// Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"encoding/json"
	"io"
	"net/http"
	"os"
	"strconv"

	"github.com/pkg/errors"

	"github.com/erda-project/erda/tools/cli/command"
	"github.com/erda-project/erda/tools/cli/common"
)

var GwDel = command.Command{
	ParentName: "Gw",
	Name:       "del",
	ShortHelp:  "Deletes package apis with the input data",
	LongHelp:   "Deletes package apis with the input data",
	Example:    "erda-cli gw del -f xxx.json",
	Flags: []command.Flag{
		command.StringFlag{
			Name: "pkg-id",
			Doc:  Doc("the package's id", "流量入口的 id", Required),
		},
		command.StringFlag{
			Name:  "input",
			Short: "i",
			Doc:   Doc("api list json file, generated by erda-cli gw dump", "api 列表文件, 由 erda-cli gw dump 生成", Required),
		},
		command.StringFlag{
			Name: "org",
			Doc:  Doc("the org name", "组织名称", Required),
		},
	},
	Run: RunGwDel,
}

func RunGwDel(ctx *command.Context, pkgID, input, orgName string) error {
	ctx.Info("RunGwDel")
	if input == "" {
		return errors.New("invalid --input")
	}
	if orgName == "" {
		if err := ctx.FetchOrgs(); err != nil {
			return err
		}
	} else {
		ctx.CurrentOrg.Name = orgName
		_, _, err := common.GetOrgID(ctx, orgName)
		if err != nil {
			return err
		}
	}

	data, err := os.ReadFile(input)
	if err != nil {
		return errors.Wrapf(err, "failed to os.Open(%s)", input)
	}
	var resp ListPackageAPIsResponse
	if err = json.Unmarshal(data, &resp); err != nil {
		return errors.Wrap(err, "failed to json.Unmarshal")
	}

	var (
		headers = http.Header{
			"Org-ID":          {strconv.FormatUint(ctx.CurrentOrg.ID, 10)},
			"Org-Name":        {ctx.CurrentOrg.Name},
			"Org":             {ctx.CurrentOrg.Name},
			"User-ID":         {ctx.GetUserID()},
			"Internal-Client": {"erda-cli"},
		}
	)
	for i := 0; i < len(resp.Data.List); i++ {
		ctx.Info("[%v] %s %s\n", i, resp.Data.List[i].ApiId, resp.Data.List[i].ApiPath)
		request := ctx.UseHepaApi().
			Delete().
			Path("/api/gateway/openapi/packages/" + pkgID + "/apis/" + resp.Data.List[i].ApiId).
			Headers(headers)
		response, err := request.Do().RAW()
		if err != nil {
			return errors.Wrap(err, "failed to do Delete")
		}
		if response.StatusCode >= 300 || response.StatusCode < 200 {
			data, _ := io.ReadAll(response.Body)
			_ = response.Body.Close()
			ctx.Error("failed to Delete [%v] %s %s %s\n", i, request.GetUrl(), response.Status, string(data))
		}
	}
	return nil
}
